<template>
  <div class="gamerule">
    <br>
    <div class="rule_item weui-flex">
      <span class="rule_item_each">收费：</span>
      <p id="costType2" class="rule_cost_aa radio" :class="{'select-item': costTypeSelect}" value="2" :check="costTypeSelect?'checked': 'unchecked'" @click="aaClick" name="costType">玩家AA付费</p>
      <p id="costType1" class="rule_cost_my radio" :class="{'select-item': !costTypeSelect}" value="1" :check="costTypeSelect?'unchecked': 'checked'" @click="bossClick" name="costType">亲友圈付费</p>
    </div>
    <br>
    <div class="rule_item rule_jushu weui-flex" v-if="jushuShow">
      <span class="rule_item_each">局数：</span>
      <p name="round" class="radio" v-for="(cost, index) in actualCost" v-bind:class="{'select-item': costSelect == index}" :check="costSelect == index ? 'checked': 'unchecked'" @click="costClick(index,$event)" :value="cost.turn" :id="'round' + cost.turn">{{cost.desc}}</p>
    </div>
    <div id="table"></div>
    <div class="rule_begin" v-bind:class="{'hidden': !ifWaitTime}">
      <div class="rule_begin_person weui-flex rule_item">
        <span>最小开始人数：</span>
        <p v-for="(person, index) in minPlayers" v-bind:class="{'select-item': personSelect == index}" :check="personSelect==index?'checked': 'unchecked'" @click="personClick(index)">{{person + '人'}}</p>
      </div>
      <div class="rule_begin_time">
        <cell title="最长等待时间：" primary="content">
          <range class="range_time" minHTML=" " maxHTML="5s" v-model="waitTime" @on-change="timeChange"></range>
        </cell>
      </div>
    </div>
    <div class="rule_item rule_xianzhi weui-flex">
      <span>限制：</span>
      <p id="allowIp" class="rule_xianzhi_ip checkbox" v-bind:class="{'select-item': ipSelect}" name="allowIp" :check="ipSelect? 'checked': 'unchecked'" value="0" @click="ipClick($event)">禁止同IP进入</p>
      <p id="allowWeizhi" class="rule_xianzhi_weizhi checkbox" v-bind:class="{'select-item': localSelect}" name="allowWeizhi" :check="localSelect ?'checked': 'unchecked'" value="0">桌内地理位置相近者禁止同时进入</p>
    </div>
    <button class="rule_btn" @click="btnSure()">确定</button>
  </div>
</template>

<script>
import { Checker, CheckerItem, Range, Cell } from "vux";
var lua = require("lua.vm.js").L;
import gamerule from "./gamerule.js";
import { getUrlString } from "../../../scripts/utils";
import { throws } from "assert";
import { clearTimeout } from "timers";
export default {
  data() {
    return {
      gameId: "",
      myCost: [],
      aaCost: [],
      waitTime: 5,
      costType: 0,
      costTypeSelect: true, //用于判断付费模式是否选中,true是aa,false是老板付费
      costSelect: 0,
      personSelect: 0,
      ipSelect: false,
      localSelect: false,
      ifWaitTime: true,
      minPlayers: [], //最小开始人数数组
      clubValue: {},
      tuolaji: {},
      aatuolaji: {},
      mytuolaji: {},
      jushuShow: true,
      actualCost: []
    };
  },
  components: {
    Checker,
    CheckerItem,
    Range,
    Cell
  },
  watch: {
    costType() {
      let temp;
      let final = [];
      let handleData = (array, ...str) => {
        final = [];
        array.map(tempItem => {
          let finalItem = "";
          let turn;
          let juOrQuan = "局";
          turn = tempItem.turn;
          if (tempItem.turn.includes("X")) {
            juOrQuan = "圈";
            turn = tempItem.turn.split("X")[1];
          }
          finalItem =
            turn + juOrQuan + "(房卡" + str[0] + tempItem.cost + str[1] + ")";
          final.push({
            desc: finalItem,
            turn: tempItem.turn,
            cost: tempItem.cost
          });
        });
        return final;
      };
      if (this.costType === 1) {
        this.costTypeSelect = false;
        this.actualCost = handleData(this.myCost, "", "张");
      } else {
        this.costTypeSelect = true;
        this.actualCost = handleData(this.aaCost, "X", "");
      }
    }
  },
  created() {
    /**
     * 每次先把club的数据取出来
     */
    this.clubValue = this.apiService.getSessionData("clubValue");
    // 对gameid进行处理
    let gameId = getUrlString("gameId");
    if (gameId) {
      this.clubValue.activityId = gameId;
    } else {
      gameId = this.clubValue.activityId;
    }
    let thisHref = location.href;
    this.gameId = gameId;
    window.gameid = gameId;
    if (this.gameId == 200001) {
      window.gameid = "200001";
      this.jushuShow = false;
    }
    let resPromise = this.apiService.club.getactivityconsumptiont({
      activityid: this.gameId
    });
    resPromise
      .then(res => {
        let result = res.data;
        // 对cost选项做处理
        let cost = JSON.parse(result.cost);
        for (const key in cost) {
          if (cost.hasOwnProperty(key)) {
            const item = cost[key];
            if (key.includes("AA")) {
              this.aatuolaji[key.split("AA")[1]] = cost[key];
              this.aaCost.push({
                turn: key.split("AA")[1],
                cost: cost[key]
              });
            } else {
              this.mytuolaji[key] = cost[key];
              this.myCost.push({
                turn: key,
                cost: cost[key]
              });
            }
          }
        }
        this.costType = 2;
        this.tuolaji = this.aatuolaji;
        window.tuolaji = this.tuolaji;
        // 对时间和最小开始人数做处理
        let maxPlayer = result.maxPlayer;
        let minPlayer = result.minPlayer;
        if (maxPlayer === minPlayer) {
          this.ifWaitTime = false;
        } else {
          for (let i = minPlayer; i <= maxPlayer; i++) {
            this.minPlayers.push(i);
          }
        }
      })
      .then(() => {
        HTMLElement.prototype.setEnabled = function(className, bool) {
          var dom = document.querySelector("." + className);
          dom.disabled = !bool;
        };
        HTMLElement.prototype.setValue = function(className, bool) {
          var dom = document.getElementsByName(className);
          if (dom.length > 1) {
            //单选框
            for (var i = 0; i < dom.length; i++) {
              var item = dom[i];
              if (item.value == bool) {
                item.setAttribute("check", "checked");
                item.classList.add("select-item");
              } else {
                item.setAttribute("check", "unchecked");
                item.classList.remove("select-item");
              }
            }
          } else {
            //复选框
            if (bool == "1") {
              dom[0].setAttribute("check", "checked");
              dom[0].classList.add("select-item");
            } else {
              dom[0].setAttribute("check", "unchecked");
              dom[0].classList.remove("select-item");
            }
          }
        };
        //导入lua代码
        let luaString = gamerule;
        lua.execute(luaString);

        //初始化cost选项的状态
        if (this.clubValue.userset) {
          // 总数据
          let initluaRules;
          if (this.clubValue.userset.round) {
            initluaRules = this.clubValue.userset;
          } else {
            initluaRules = JSON.parse(this.clubValue.userset);
          }
          //初始化lua规则
          for (var initluaRule in initluaRules) {
            if (initluaRules.hasOwnProperty(initluaRule)) {
              var selectLuaItem = document.querySelector(
                "#" + initluaRule + initluaRules[initluaRule]
              );
              if (selectLuaItem) {
                selectLuaItem.click();
              } else {
                selectLuaItem = document.querySelector("#" + initluaRule);
                if (
                  selectLuaItem &&
                  selectLuaItem.getAttribute("value") !==
                    initluaRules[initluaRule]
                ) {
                  selectLuaItem.click();
                }
              }
            }
          }
        }
      });
  },
  beforeRouteLeave(from, to, next) {
    this.apiService.setSessionData("clubValue", this.clubValue);
    next();
  },
  methods: {
    timeChange() {
      let rangeMax = document.querySelector(".range-max");
      rangeMax && (rangeMax.innerHTML = this.waitTime + "s");
    },
    aaClick() {
      this.costType = 2;
    },
    bossClick() {
      this.costType = 1;
    },
    costClick(index, event) {
      this.costSelect = index;
    },
    personClick(index) {
      this.personSelect = index;
    },
    ipClick(event) {
      this.ipSelect = !this.ipSelect;
    },
    btnSure() {
      /**
       * 终极确定按钮
       */
      let userset = {};
      // 取出所有的单选框选中的按钮
      let radios = document.querySelectorAll(".radio");
      for (let a = 0; a < radios.length; a++) {
        let radiositem = radios[a];
        if (radiositem.getAttribute("check") === "checked") {
          let myName = radiositem.getAttribute("name");
          let myValue = radiositem.getAttribute("value");
          if (myName != null) {
            userset[myName] = myValue;
          }
        }
      }
      //取出所有的复选框的选中的选项
      let checks = document.querySelectorAll(".checkbox");
      for (let b = 0; b < checks.length; b++) {
        let checksitem = checks[b];
        let myName = checksitem.getAttribute("name");
        let value = "0";
        if (checksitem.getAttribute("check") === "checked") {
          value = "1";
        }
        userset[myName] = value;
      }
      //是否允许相同的IP或者位置进入
      let allowIp = this.ipSelect ? 1 : 0;
      // var allowWeizhi = ruleXianzhiWeizhiBtn.classList.contains('select-item') ? 1 : 0
      // 将规则赋值给全局变量
      window.userset = userset;
      let rule = lua.execute("return getRule()");
      let issetPlayer = lua.execute("return getPlayerCount()");

      // 创建一个数据对象(展示所用)

      var showrules = {};

      let selectCostType = this.costTypeSelect ? "2" : "1";

      showrules.showmode = selectCostType === "1" ? "房主付费" : "玩家AA收费";
      showrules.showSelectRules =
        this.actualCost[this.costSelect].desc + rule[0].split("invitedesc=")[1];
      this.clubValue.showrules = showrules;
      if (!this.isWaitTime) {
        this.waitTime = 0;
      }
      //创建一个游戏规则对象(上传接口所用)
      this.clubValue.cost = this.actualCost[this.costSelect].cost; //房卡消耗
      this.clubValue.costType = selectCostType; //房卡消耗模式，1 是房主付费，2是玩家付费
      this.clubValue.minPlayer = this.minPlayers[this.personSelect] || 0; //最小等待开始人数
      this.clubValue.notAllowSameIp = allowIp; //是否允许相同ip的人进入
      this.clubValue.round = this.actualCost[this.costSelect].turn; // 选择的局数
      if (window.gameid == 200001) {
        var rounds = document.querySelectorAll(".round");
        for (var q = 0; q < rounds.length; q++) {
          if (rounds[q].getAttribute("check") == "checked") {
            this.clubValue.cost = rounds[q].querySelector("span").innerHTML;
            this.clubValue.round = rounds[q].getAttribute("value");
          }
        }
      }
      this.clubValue.ruler = rule[0]; //lua那边传过来的规则
      this.clubValue.waitTime = this.waitTime; //等待时间
      if (issetPlayer[0] !== false) {
        this.clubValue.playerCount = issetPlayer[0];
      }
      this.clubValue.userset = window.userset;

      var clubTitle = getUrlString("gamename");
      if (clubTitle) {
        this.clubValue.activityName = decodeURIComponent(clubTitle);
      }
      var reqData = {
        clubid: this.clubValue.clubId,
        cost: this.clubValue.cost,
        costtype: this.clubValue.costType,
        round: this.clubValue.round,
        ruler: this.clubValue.ruler,
        notAllowSameIP: this.clubValue.notAllowSameIp,
        allowSameLocation: this.clubValue.allowSameLocation,
        minPlayer: this.clubValue.minPlayer,
        userset: this.clubValue.userset
      };
      if (this.clubValue.waitTime) {
        reqData.waitTime = this.clubValue.waitTime;
      }
      if (issetPlayer[0] !== false) {
        reqData.playerCount = issetPlayer[0];
      }
      if (getUrlString("mode") == "edit") {
        if (this.clubValue.clubId) {
          this.apiService.club.editclub(reqData).then(res => {
            return history.go(-1);
          });
        } else {
          if (getUrlString("create") == "yes") {
            return history.go(-3);
          }
          history.go(-1);
        }
      } else {
        //不是编辑的话跳转到下一页
        this.$router.push("title");
      }
    }
  }
};
</script>

<style>
.gamerule {
  background-color: #f5f5f5;
  padding: 5px 15px;
  font-size: 14px;
}
.gamerule .weui-cell {
  padding-left: 0;
}
.select {
  display: inline-block;
}

.default_select {
  border: 1px solid red;
}

.select-item {
  background-color: #2bbc6a;
  border-color: #2bbc6a;
  border-radius: 6px;
  color: #fff;
  padding: 7px 10px;
  margin-right: 10px;
}

.rule_item {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.rule_item p {
  border: 1px solid #555;
  border-radius: 6px;
  color: #555;
  font-size: 0.24rem;
  padding: 0.15rem;
  margin: 10px 10px 10px 0;
}

.rule_item .select-item {
  background-color: #2bbc6a;
  border-color: #2bbc6a;
  color: #fff;
}

.rule_xianzhi_weizhi {
  display: none;
}

.radio {
  margin-right: 10px;
}

#table .select-item {
  color: #fff;
  border-color: #2bbc6a;
}

#table button {
  margin: 10px 10px 10px 0;
  border: 1px solid #555;
  border-radius: 6px;
  color: #555;
  font-size: 0.24rem;
  line-height: 1;
  height: 36.5px;
  padding: 0.15rem;
}

.time_slider {
  margin: 15px 0;
}

.rule_btn {
  background-color: #00ac34;
  border-radius: 0.1rem;
  color: #fff;
  display: block;
  font-size: 0.4rem;
  height: 0.89rem;
  margin: 25px auto 0;
  width: 92%;
}

.hidden {
  display: none;
}

.rule_item_each {
  font-size: 0.24rem;
}

.logo {
  border-radius: 50%;
  margin-right: 0.1rem;
  vertical-align: middle;
}
</style>

